package com.libbase.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.base.activity.BaseActivity;
import com.base.load.DefaultLoad;
import com.chan.net.HttpCallback;
import com.flyco.tablayout.SlidingTabLayout;
import com.libbase.LibApplication;
import com.libbase.R;
import com.libbase.adapter.NyqfAdapter;
import com.libbase.bean.NyqfBean;
import com.libbase.fragment.NewFragment;
import com.libbase.glide.GlideUtil;
import com.libbase.manager.NyqfManager;
import com.libbase.widget.MindleViewPager;
import com.libbase.widget.NavigationTabView;
import com.libtask.ThreadHelper;
import com.squareup.haha.guava.collect.ArrayListMultimap;
import com.squareup.leakcanary.RefWatcher;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import com.uitls.utils.AnimationUtil;

import org.yczbj.ycvideoplayerlib.controller.VideoPlayerController;
import org.yczbj.ycvideoplayerlib.manager.VideoPlayerManager;
import org.yczbj.ycvideoplayerlib.player.VideoPlayer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

public class NyqfActivity extends BaseActivity implements AppBarLayout.OnOffsetChangedListener, LifecycleProvider<ActivityEvent>, NewFragment.FragmentCallBack {

    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, NyqfActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.rcy_main)
    SlidingTabLayout rcyMain;
    @BindView(R.id.main_abl_appbar)
    AppBarLayout mainAblAppbar;
    @BindView(R.id.main_vp)
    ViewPager mainVp;
    @BindView(R.id.fl_content)
    FrameLayout flContent;

    DefaultLoad loadView;
    private float mTitleBarHeight;
    protected float mLastScale = 1;
    protected float mLastAlpha = 1;

    //    List<BaseFragment> fragmentList;
    List<NavigationTabView> navigationTabViewList;

    int select = -1;

    final String FIRST_INDEX = "index";
    final String SECEND_INDEX = "dangjian";
    final String THIRD_INDEX = "me";

    private VideoPlayer mVideoView;
    ArrayListMultimap<String, String> titleListMultimap;
    ArrayListMultimap<String, String> listMultimap;
    NyqfAdapter pagerAdapter;

    @BindView(R.id.rb_cpp_main)
    NavigationTabView rbCppMain;

    @BindView(R.id.rb_cpp_dang)
    NavigationTabView rbCppDang;

    @BindView(R.id.rb_cpp_mine)
    NavigationTabView rbCppMine;

    @BindView(R.id.ll_cpp_buttom)
    LinearLayout llCppButtom;
    @BindView(R.id.bannerview)
    MindleViewPager bannerview;
    @BindView(R.id.ll_top)
    LinearLayout llTop;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_nyqf;
    }

    @Override
    protected boolean useDynamicTitleBar() {
        return false;
    }

    @Override
    protected boolean isTranslucentStatus() {
        return true;
    }

    /**
     * https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543896079910&di=688ecbe129f12b277a33447e11dc2880&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01d18159a8c8f5a801211d25b8b6fa.jpg%402o.jpg
     *
     * @param savedInstanceState
     */

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);

        mTitleBarHeight = getResources().getDimension(R.dimen.title_bar_height) + getResources().getDimension(R.dimen.dp150);
        mainAblAppbar.setPadding(0, getStatusBarHeight(), 0, 0);

        pagerAdapter = new NyqfAdapter(getSupportFragmentManager());
        mainVp.setAdapter(pagerAdapter);

        titleListMultimap = ArrayListMultimap.create();
        listMultimap = ArrayListMultimap.create();

        rbCppMain.setRadioButtonBG(R.mipmap.main_selected, R.mipmap.main_unselected, "首页");
        rbCppDang.setRadioButtonBG(R.mipmap.nyqf_selected, R.mipmap.nyqf_unselected, "反腐倡廉");
        rbCppMine.setRadioButtonBG(R.mipmap.me_selected, R.mipmap.me_unselected, "我");
        navigationTabViewList = Arrays.asList(rbCppMain, rbCppDang, rbCppMine);

        bannerview.setAdapter(new MindleViewPager.LunAdapter() {
            @Override
            public View getview(ViewGroup container, List list, int position) {
                ImageView imageView = new ImageView(mContext);
                GlideUtil.loadArcRectangleImage(imageView, list.get(position), R.dimen.dp5);
                return imageView;
            }
        }, Arrays.asList("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564396852644&di=4ab24fcef53d37ca7b6e16ec6b6f6a9b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201409%2F19%2F20140919033302_FrnUy.jpeg",
                "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543899454775&di=f6b657adc35d3614c474eeec42bb0dae&imgtype=0&" +
                        "src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01d4c959afa1f9a8012028a9fd5f9a.jpg%401280w_1l_2o_100sh.jpg"));

        //
        loadView = new DefaultLoad(mContext);
        select(0);

        loadView.load(flContent);
        NyqfManager.getnyqfTitles(this, new HttpCallback<NyqfBean>() {
            @Override
            public void onSuccess(String requestCommand, NyqfBean bean) {
                for (NyqfBean.NavBean navBean : bean.getNav()) {
                    initIndex(navBean);
                }
                initMeIndex();
                bindDataView();
            }

            @Override
            public void onFail(String requestCommand, int code, String msg) {

            }
        });
    }

    @Override
    protected void release() {
        listMultimap.clear();
        RefWatcher refWatcher = LibApplication.getInstance().getRefWatcher();//1
        refWatcher.watch(this);
    }

    /**
     * 绑定数据to View
     */
    private void bindDataView() {
        final int position = (select == -1) ? 0 : select;
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            loadView.removeView();
            select = -1;
            select(position);
        } else {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    loadView.removeView();
                    select = -1;
                    select(position);
                }
            });
        }
    }

    void select(int position) {
        if (select != position) {
            select = position;
            for (NavigationTabView navigationTabView : navigationTabViewList) {
                navigationTabView.setCheck(false);
            }
            navigationTabViewList.get(position).setCheck(true);
            bindTitle(position);
        }
    }

    void bindTitle(int position) {
        if (listMultimap.size() > 0) {
            List<String> dataBeans = null;
            List<String> strings = null;
            switch (position) {
                case 0:
                    dataBeans = listMultimap.get(FIRST_INDEX);
                    strings = titleListMultimap.get(FIRST_INDEX);
                    break;
                case 1:
                    dataBeans = listMultimap.get(SECEND_INDEX);
                    strings = titleListMultimap.get(SECEND_INDEX);
                    break;
                case 2:
                    dataBeans = listMultimap.get(THIRD_INDEX);
                    strings = titleListMultimap.get(THIRD_INDEX);
                    break;
            }
            if (dataBeans != null && !dataBeans.isEmpty()) {
                mainVp.setOffscreenPageLimit(dataBeans.size());
                String[] title = new String[strings.size()];
                title = strings.toArray(title);
                pagerAdapter.setTitles(strings);
                pagerAdapter.setNewData(dataBeans);
                rcyMain.setViewPager(mainVp, title);
                pagerAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 页面标题处理
     *
     * @param navBean
     */
    private void initIndex(NyqfBean.NavBean navBean) {
        if (navBean.getCode().equalsIgnoreCase(FIRST_INDEX)) {
            initFirstIndex(navBean);
        } else {
            initOthersIndex(navBean);
        }
    }

    /**
     * 首页
     *
     * @param navBean
     */
    private void initFirstIndex(NyqfBean.NavBean navBean) {
        List<NyqfBean.DataBean> dataBeans = new ArrayList<>(navBean.getData());
        dataBeans.addAll(Arrays.asList(new NyqfBean.DataBean("", "直播"), new NyqfBean.DataBean("", "视频")));
        for (NyqfBean.DataBean dataBean : dataBeans) {
            titleListMultimap.put(FIRST_INDEX, dataBean.getTitle());
            listMultimap.put(FIRST_INDEX, dataBean.getCode());
        }
    }

    /**
     * 其他页面
     *
     * @param navBean
     */
    private void initOthersIndex(NyqfBean.NavBean navBean) {
        for (NyqfBean.DataBean dataBean : navBean.getData()) {
            titleListMultimap.put(navBean.getCode(), dataBean.getTitle());
            listMultimap.put(navBean.getCode(), dataBean.getCode());
        }
    }

    /**
     * 我的页面
     */
    private void initMeIndex() {
        NyqfBean.DataBean dataBean = new NyqfBean.DataBean();
        dataBean.setTitle("我");
        titleListMultimap.put(THIRD_INDEX, "我");
        listMultimap.put(THIRD_INDEX, dataBean.getCode());
    }


    @OnClick({R.id.rb_cpp_main, R.id.rb_cpp_dang, R.id.rb_cpp_mine})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_cpp_main:
                select(0);
                break;
            case R.id.rb_cpp_dang:
                select(1);
                break;
            case R.id.rb_cpp_mine:
                select(2);
                break;
        }
    }

    /**
     * 清除videoView的父view
     */
    @Override
    public void removePlayerView() {
        if (mVideoView == null) {
            return;
        }
        if (mVideoView.getParent() != null) {
            ViewGroup viewGroup = (ViewGroup) mVideoView.getParent();
            viewGroup.removeView(mVideoView);
        }
        mVideoView.release();
        VideoPlayerManager.instance().releaseVideoPlayer();
    }

    @Override
    public VideoPlayer getVideoView() {
        if (mVideoView == null) {
            mVideoView = new VideoPlayer(mContext);
            VideoPlayerController controller = new VideoPlayerController(mContext);
            controller.setTitle("");
            mVideoView.setController(controller);
        }
        return mVideoView;
    }

    /**
     * 是否有父view
     *
     * @return
     */
    @Override
    public boolean hasVideoViewParent() {
        if (mVideoView == null) {
            return false;
        } else {
            if (mVideoView.getParent() != null) {
                return true;
            }
            return false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mainAblAppbar.addOnOffsetChangedListener(this);
        lifecycleSubject.onNext(ActivityEvent.RESUME);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mainAblAppbar.removeOnOffsetChangedListener(this);
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        scaleTitleBar(verticalOffset);
    }

    /**
     * 缩放titlebar
     *
     * @param verticalOffset
     */
    protected void scaleTitleBar(int verticalOffset) {
        float offsetPercent = verticalOffset / mTitleBarHeight;
        float toScale = 1 + (offsetPercent * 3 / 7F);
        float toAlpha = 1 + (offsetPercent * 10 / 7F);
        ScaleAnimation leftScaleAnimation = null;
        ScaleAnimation rightScaleAnimation = null;
        ScaleAnimation scaleAnimation = null;
        AlphaAnimation alphaAnimation = null;
        if (mLastScale != toScale) {
            leftScaleAnimation = new ScaleAnimation(mLastScale, toScale, mLastScale, toScale, Animation.RELATIVE_TO_SELF, 1F, Animation.RELATIVE_TO_PARENT, 1F);
            rightScaleAnimation = new ScaleAnimation(mLastScale, toScale, mLastScale, toScale, Animation.RELATIVE_TO_SELF, 0F, Animation.RELATIVE_TO_PARENT, 1F);
            scaleAnimation = new ScaleAnimation(mLastScale, toScale, mLastScale, toScale, Animation.RELATIVE_TO_SELF, 0.5F, Animation.RELATIVE_TO_PARENT, 1F);
            mLastScale = toScale;
        }
        if (mLastAlpha != toAlpha && toAlpha <= 1) {
            alphaAnimation = new AlphaAnimation(mLastAlpha, toAlpha);
            mLastAlpha = toAlpha;
        }
        if (scaleAnimation != null || alphaAnimation != null) {
            //AnimationUtil.startAnimation(getTitleBar().getLeftView(), leftScaleAnimation, alphaAnimation);
            AnimationUtil.startAnimation(rcyMain, alphaAnimation);
            //AnimationUtil.startAnimation(getTitleBar().getRightView(), rightScaleAnimation, alphaAnimation);
        }
        if (mTitleBarHeight + verticalOffset == 0) {    //完全移除屏幕
            if (mainAblAppbar.getAlpha() == 1) {
                mainAblAppbar.setAlpha(0.9F);
            }
        } else {
            if (mainAblAppbar.getAlpha() != 1) {
                mainAblAppbar.setAlpha(1F);
            }
        }
    }

    @Override
    public Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    public <T> LifecycleTransformer<T> bindUntilEvent(ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }


    @Override
    public <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }


    @Override
    @CallSuper
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lifecycleSubject.onNext(ActivityEvent.CREATE);
    }

    @Override
    @CallSuper
    protected void onStart() {
        super.onStart();
        lifecycleSubject.onNext(ActivityEvent.START);
    }


    @Override
    @CallSuper
    protected void onStop() {
        lifecycleSubject.onNext(ActivityEvent.STOP);
        super.onStop();
    }

    @Override
    @CallSuper
    protected void onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
        super.onDestroy();
    }
}
